import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:native_dart_package/native_dart_package.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yt_devops/components/list_empty_widget.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/configs.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/site_elec_price_setting_model.dart';
import 'package:yt_devops/pages/site/site_setting/siet_elec_price_setting/site_list_item_view.dart';
import 'package:yt_devops/routers/router_path.dart';
import 'package:yt_devops/utils/enums.dart';

import '../../../../components/tips.dart';

class SiteListView extends StatefulWidget {
  const SiteListView(
      {super.key,
      required this.service,
      required this.siteId,
      required this.type,
      required this.monetaryUnitName,
      required this.index});

  final int siteId;
  final Future Function(Map) service;
  final ElecPriceType? type;
  final String monetaryUnitName;
  final int index;

  @override
  State<StatefulWidget> createState() {
    return SiteListViewState();
  }
}

class SiteListViewState extends State<SiteListView>
    with AutomaticKeepAliveClientMixin {
  RefreshController refreshController =
      RefreshController(initialRefresh: false);
  int pageNum = 1;
  int pageSize = 10;
  List<SiteElecPriceSettingModel>? state = [];

  // 过滤参数
  Map<String, dynamic> extraParam = {};

  @override
  void initState() {
    super.initState();
    Log.d('SiteListViewState===');
    loadList();
  }

  Future<void> loadList() async {

    extraParam['siteId'] = widget.siteId;
    var params = {'current': pageNum, 'pageSize': pageSize, ...extraParam};
    var data = await widget.service(params);
    Log.d('loadList===' + data.toString());
    refreshController.loadComplete();
    refreshController.refreshCompleted();
    var temp = List.of(data['list'])
        .map((item) => SiteElecPriceSettingModel.fromJson(item))
        .toList();
    Log.d('loadList===' + temp.length.toString());
    if (pageNum == 1) {
      state?.clear(); // 清空
    }
    state?.addAll(temp);
    if (data['total'] != null && data['total'] <= state?.length) {
      refreshController.loadNoData();
    }
    setState(() {

    });
  }

  void onRefresh() {
    pageNum = 1;
    Log.d('state===onRefresh' + widget.type.toString());
    loadList();
  }

  void onLoad() {
    pageNum++;
    loadList();
  }

  toDetails(int id) {
    String path = '';
    Map<String, dynamic> arguments = {
      'id': id,
      'siteId': widget.siteId,
      'monetaryUnitName': widget.monetaryUnitName,
    };
    if (widget.type == ElecPriceType.mains) {
      //市电
      path = RouterPath.siteMainsElecDetail;
    } else if (widget.type == ElecPriceType.store) {
      //储能
      path = RouterPath.energyStoreageDischargePriceController;
      arguments['isEnableEdit'] = false;
    } else if (widget.type == ElecPriceType.internet) {
      //光伏上网
      path = RouterPath.siteInternetElecDetail;
    } else {
      path = RouterPath.siteChargeElecDetail;
    }

    Get.toNamed(path, arguments: arguments)?.then((value) {
      if (value == true) {
        onRefresh();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return SmartRefresher(
      controller: refreshController,
      enablePullDown: true,
      enablePullUp: true,
      // header: const MaterialClassicHeader(),
      header: ListTips.classicHeader,
      footer: ListTips.generateClassicFooter,
      onLoading: () => onLoad(),
      onRefresh: () => onRefresh(),
      child: listBody(),
    );
  }

  Widget listBody() {
    Log.d('state===' + widget.type.toString());
    if (state == null) {
      return const SizedBox.shrink();
    } else if (state!.isEmpty) {
      return ListEmptyWidget(topPosition: 82);
    } else {
      return ListView.builder(
        padding: EdgeInsets.symmetric(vertical: 10.h),
        physics: const AlwaysScrollableScrollPhysics(),
        // padding: EdgeInsets.fromLTRB(15.w, 95.h, 15.w, 10.h),
        itemBuilder: (context, index) {
          if ((state!.isEmpty)) {
            return ListEmptyWidget(topPosition: 82);
          } else {
            var data = state![index];
            return SiteListItemView(
              type: $enumDecodeNullable($ElecPriceTypeEnumMap, widget.index),
              model: data,
              onItemTaped: (model) => toDetails(model.id!),
            );
          }
        },
        itemCount: state!.length,
      );
    }
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
